import axios from 'axios'
import Store from '@/store'
import router from '@/router'
import { Message } from 'element-ui'
const _axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API
})
_axios.interceptors.request.use(
  (config) => {
    if (Store.state.user.token) {
      config.headers.Authorization = 'Bearer ' + Store.state.user.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
_axios.interceptors.response.use(
  (res) => {
    const { success, message } = res.data
    if (success) {
      return res.data
    } else {
      Message.error(message)
      return Promise.reject(message)
    }
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      // token失效   400 === 参数错误
      // 清空token , 清空用户信息, 提示用户, 跳转到登录页带上页面地址参数
      // 路由赋值与传值
      Store.commit('user/loginOut')
      Message.error(error.response.data.message)
      router.push('/login?add=' + window.location.href.split('#')[1])
    }
    return Promise.reject(error)
  }
)
export default _axios
